package traceability

import (
	"context"
	"encoding/json"
	"group-card/common/response"
	"group-card/rpc/card/cardclient"

	"group-card/api/internal/svc"
	"group-card/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type TraceabilityAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewTraceabilityAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TraceabilityAddLogic {
	return &TraceabilityAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *TraceabilityAddLogic) TraceabilityAdd(req *types.AddTraceabilityRequest) (resp *types.TraceabilityResponse, err error) {
	_, err = l.svcCtx.Card.TraceabilityAdd(l.ctx, &cardclient.TraceabilityAddRequest{
		CardNumber:     req.CardNumber,
		StorageAdminId: req.StorageAdminId,
		StorageTime:    req.StorageTime,
		PublishAdminId: req.PublishAdminId,
		PublishTime:    req.PublishTime,
		ReceiveAdminId: req.ReceiveAdminId,
		ReceiveTime:    req.ReceiveTime,
		BindingUserId:  req.BindingUserId,
		BindingTime:    req.BindingTime,
		WriteOffTime:   req.WriteOffTime,
		Status:         req.Status,
	})

	if err != nil {
		reqStr, _ := json.Marshal(req)
		logx.WithContext(l.ctx).Errorf("添加溯源发行失败,参数:%s,异常:%s", reqStr, err.Error())
		return &types.TraceabilityResponse{Code: response.ErrCode, Message: "添加卡片溯源失败"}, nil
	}

	return &types.TraceabilityResponse{
		Code:    response.SuccessCode,
		Message: "添加卡片溯源成功",
	}, nil

}
